<?php

namespace App\Jobs\QiPao\Draw;

use App\Jobs\Job;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class SeniorDrawFullGiftJob extends Job
{
    protected $templatePrizes;
    protected $poolGroupInfo;
    protected $cachePrefix;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($templatePrizes, $poolGroupInfo, $cachePrefix)
    {
        $this->templatePrizes = $templatePrizes;
        $this->poolGroupInfo        = $poolGroupInfo;
        $this->cachePrefix    = $cachePrefix;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $redisObject    = app('redis')->connection('game');

            $templatePrizes = $this->templatePrizes;
            $sumCount       = $templatePrizes->sum('count');
            $prizeList      = $templatePrizes->toArray();
            if ($sumCount < 1) {
                return null;
            }

            //根据剩余数量进行权重抽取
            $prizeId = 0;
            $groupId = 0;
            //权重总值
            $totalWeight = $sumCount;
            $randomId    = mt_rand(1, $totalWeight);
            $weight      = 0;
            $drawPrizes  = [];
            while ($sumCount) {
                foreach ($prizeList as &$mPool) {
                    if ($randomId > $weight && $randomId <= ($mPool['count'] + $weight)) {
                        $prizeId = $mPool['gift_template_id'];
                        $groupId = $mPool['group_id'];
                        $mPool['count']--;
                        $totalWeight--;
                        $weight = 0;
                        break;
                    } else {
                        $weight += $mPool['count'];
                    }
                }
                if ($totalWeight > 0) {
                    $randomId = mt_rand(1, $totalWeight);
                }

                $drawPrizes[] = $groupId . "_" . $prizeId;
                $sumCount--;
            }
            //$templatePrizes
            //往redis list右边推送新的礼物列表
            $redisObject->rpush($this->cachePrefix . "prizeList_" . $this->poolGroupInfo['tag'], $drawPrizes);
            $redisObject->expire($this->cachePrefix. "fullPollLock_" . $this->poolGroupInfo['tag'], 5);
//            // 清空本轮礼物总数
            app('model_senior_pool_prize')->updateData(['group_id' => $this->poolGroupInfo['group_id']], ['template_count' => 0]);
            app('model_senior_pool_prize')->appendPrizes($this->poolGroupInfo, $templatePrizes);
        } catch (\Exception $e) {
            Log::error('萌宠抽奖补充错误：' . $e->getMessage());
        }

    }

    /* public function fail($exception = null )
     {
         Log::error('giftJob:'.$exception->getMessage());
     }*/
}
